<?php
namespace Admin\Controller;
use Think\Controller;

class IndexController extends CommonController{
    //后台管理首页
    public function index(){
        $username=isset($_GET['username'])? $_GET['username']:session('username');
        $this->assign('username',$username);
        $this->display();
   }

    //用户添加
    public function addUser(){
        $role=M('role')->field('role_id,role_name')->select();
        $this->assign('roleInfo',$role);
        $this->display();
    }

    //处理添加用户请求
    public function handleAddUser(){
        $arr=$_POST;
        $arr['create_time']=time();
        $Admin=D('Admin');
        if(!$Admin->create($arr)){
            $this->redirect('adduser', "",'2','此账号已存在，请重新输入！');
        }else{
            if(M('Admin')->add($arr)){
                $this->redirect('indexuser',"",'2','添加成功，正在跳转！');
            }else{
                $this->error('添加失败');
            }
        }

    }
    //用户编辑
    public function editUser(){
        $id= $_GET['id'];//获取用户id
        $user=M('Admin')->where('id=%d',$id)->field('id,account,password,username,email,status')->find();
        $this->assign("userInfo",$user);
        $this->display();
    }
//删除用户
    public function delUser(){
        if(IS_POST){
            $id=I('post.id');
            if(M('Admin')->where(array('id'=>$id))->delete()){
                $this->ajaxReturn(1);
            }else{
                $this->ajaxReturn(0);
            }
        }
    }

    public function handleEdit(){
        $arr=$_POST;
        if(M('Admin')->where('id=%d',$arr['id'])->save($arr)){
            $this->redirect('indexUser', "",'1','修改成功,页面跳转中...');
        }else{
            $this->error('修改失败');
        }

    }
    //用户首页
    public function indexUser(){
        $username=I('post.username');
        $Model=M('Admin');
        $count= $Model->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        if(empty($username)){
            $list = $Model->order('create_time asc')->limit($Page->firstRow.','.$Page->listRows)->field('id,account,username,email,login_time,status')->select();

        }else{
            $map['username']=array('like','%'.$username.'%');
            $list=$Model->order('create_time asc')->where($map)->limit($Page->firstRow.','.$Page->listRows)->field('id,account,username,email,login_time,status')->select();
        }
       foreach($list as $key=>$value){
            $list[$key]['login_time']=date('Y-m-d H:i:s',$value['login_time']);
        }
        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

}